<?php

namespace app\api\controller\manage;

use app\admin\model\AdminLog;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Auth;
use app\common\model\Attachment;
use think\Config;
use think\Db;
use think\Hook;
use think\Request;
use think\File;
use think\Session;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;
        $code='xingkangzhihuishiji';
        $token=Request::instance()->param('token');
        if(!$token){
            $this->error('非法请求');
        }

        $iscorrect=hash_equals($token,hash('sha256',$code));
        if(!$iscorrect){
            $this->error('token');
        }
    }
    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    public function is_check(){
        $phone = $this->request->param('phone');
        if(!$phone){
            $this->error('手机号为空');
        }
        $info = Db::name('admin')->field('id,username,nickname,avatar,mobile')->where(array('mobile'=>$phone,'status'=>'normal'))->find();
        if(!$info){
            $this->error('该账号不存在，请联系管理员');
        }
        $group=Db::name('auth_group ag')
            ->join('auth_group_access aga','ag.id=aga.group_id')->field('ag.name')->where(array('aga.uid'=>$info['id']))->select();
        $group_str='';
        foreach($group as $k=>$v){
            $group_str.=$v['name'].',';
        }
        $info['group_str']=rtrim($group_str,',');
        $result['user_info'] = $info;
        $date=date('Y-m-d',time());

        $planinfo = Db::name('checkplan_detial cd')
            ->join('checkplan cp','cp.id = cd.checkplan_id')
            ->join('check_dailay c','c.check_plan_id=cd.checkplan_id')
            ->field('cp.id as plan_id,cp.checkplan,cp.check_line,cd.id as detail_id,cd.start_time,cd.end_time')
            ->where(array('cd.check_user_id'=>$info['id'],'c.status'=>1,'c.date_start'=>array('elt',$date),'c.date_end'=>array('egt',$date)))
            ->select();

        if(!$planinfo){
            $result['plan']='';
            $result['point']='';
            $result['time_range']='';
            $this->error('没有巡检安排',$result);
//            $this->error('没有巡检安排');
        }
        //方案

        $plandailay=Db::name('check_dailay')->field('check_plan_id')->where(array('status'=>1,'date_start'=>array('elt',$date),'date_end'=>array('egt',$date)))->find();



        $plan=Db::name('checkplan')->field('id,checkplan,check_line')->where(array('id'=>$plandailay['check_plan_id']))->find();
        $result['plan']=$plan;
        $line=explode(',',$plan['check_line']);
        foreach ($line as $key => $value) {
            $point=Db::name('checkpoint')->field('id,checkpoint')->where(array('id'=>$value))->find();
            $result['point'][]=$point;
        }
        $time_range=Db::name('checkplan_detial')->field('id,checkplan_id,start_time,end_time')->where(array('checkplan_id'=>$plan['id'],'check_user_id'=>$info['id']))->select();
        $result['time_range']=$time_range;

//        echo '<pre />';
//        var_dump($phone);
//        echo Db::getLastSql();die;


        $this->success('请求成功',$result);
    }
    public function has_check(){
        $detial_id = $this->request->param('detial_id');
        $check_user_id = $this->request->param('check_user_id');
        $date=date('Y-m-d',time());
        $point=Db::name('check_record')->field('checkpoint_id,checkpoint')->where(array('check_user_id'=>$check_user_id,'checkplan_detail_id'=>$detial_id,'date'=>$date))->select();
//        echo '<pre />';
//        var_dump($point);
//        echo Db::getLastSql();die;
        $this->success('请求成功',$point);
    }
    public function do_check()
    {
        $point_id = $this->request->param('point_id');
        $point=Db::name('checkpoint')->field('id,checkpoint,is_pic,status')->where(array('id'=>$point_id))->find();
        if($point['status']==2){
            $this->error('该巡检点已禁用，请联系管理员');
        }

//        echo '<pre />';
//        var_dump($phone);
//        echo Db::getLastSql();die;
        $this->success('请求成功',$point);
    }

    public function confirm_check(){
        $point_id = $this->request->param('point_id');
        $check_user_id = $this->request->param('check_user_id');
        $detial_id = $this->request->param('detial_id');
        $check_pics = $this->request->param('check_pics');
        $checkplan_id = $this->request->param('checkplan_id');
        $date=date('Y-m-d',time());
        $is_check=Db::name('check_record')->where(
            array(
                'checkpoint_id'=>$point_id,
                'check_user_id'=>$check_user_id,
                'checkplan_detail_id'=>$detial_id,
                'checkplan_id'=>$checkplan_id,
                'date'=>$date,
            )
        )->find();

        if($is_check){
            $this->error('该巡检点已巡检完成');
        }
        $datetime=date('Y-m-d H:i:s',time());
        $data=array(
            'check_user_id'=>$check_user_id,
            'checkplan_detail_id'=>$detial_id,
            'checkpoint_id'=>$point_id,
            'check_pics'=>$check_pics,
            'date'=>$date,
            'checkplan_id'=>$checkplan_id,
            'check_time'=>$datetime,
            'create_time'=>$datetime,
        );
        $plan=Db::name('checkplan')->where(array('id'=>$checkplan_id))->find();
        $data['checkplan']=$plan['checkplan'];
        $plan_detail=Db::name('checkplan_detial')->where(array('id'=>$detial_id))->find();
//        echo '<pre />';
//        var_dump($plan_detail);
//        echo Db::getLastSql();die;

        if($datetime<$date.' '.$plan_detail['start_time']){
            $data['is_abnormal']=2;
            $data['abnormal_desc']='早于该方案的设定时间';
        }
        if($datetime>$date.' '.$plan_detail['end_time']){
            $data['is_abnormal']=2;
            $data['abnormal_desc']='晚于该方案的设定时间';
        }
        $data['checkplan_detail_start_time']=$plan_detail['start_time'];
        $data['checkplan_detail_end_time']=$plan_detail['end_time'];
        $user_info=Db::name('admin')->where(array('id'=>$check_user_id))->find();

        $data['check_user']=$user_info['nickname'];
        $point=Db::name('checkpoint')->where(array('id'=>$point_id))->find();
        $data['checkpoint']=$point['checkpoint'];
        $point_id_list=explode(',',rtrim($plan['check_line'],','));
//        var_dump($point_id_list);echo $point_id;die;
        foreach ($point_id_list as $key => $value) {
            if ($value==$point_id){
                if(isset($point_id_list[$key+1])){
                    $data['next_checkpoint_id']=$point_id_list[$key+1];
                    $nextpoint=Db::name('checkpoint')->where(array('id'=>$point_id_list[$key+1]))->find();
                    $data['next_checkpoint']=$nextpoint['checkpoint'];
                }
            }
        }
        db('check_record')->insert($data);
        $this->success('提交成功');
    }

    public function upload(Request $request)
    {

        // 获取表单上传文件
        $file = $request->file('file');

        // 上传图片并获取保存信息
        $info = $file->validate(['size'=>10240000,'ext'=>'jpg,png,gif'])->move( 'uploads/checkpics');

        if ($info) {
            // 成功上传后 获取上传信息
            $filePath = '/uploads/checkpics/' . str_replace('\\', '/', $info->getSaveName());
            // 返回json数据
            return json(['status' => 'success', 'filePath' => $filePath]);
        } else {
            // 返回错误信息
            return json(['status' => 'error', 'message' => $file->getError()]);
        }
    }

}
